package auth

import (
	"github.com/gin-gonic/gin"
	logic2 "iot-base/auth/api/logic"
	Log "iot-base/auth/logger"
	"iot-base/auth/types"
	"iot-base/common/jwt"
	"strconv"
	"strings"
)

// JWTAuth 中间件，检查token
func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		resp := types.NewResult(c)
		token := c.Request.Header.Get("authToken")
		if token == "" {
			resp.ErrorCode(types.TokenNotAuth, "请求未携带token，无权限访问")
			c.Abort()
			return
		}

		//Log.Log.Info("get token: ", token)
		j := jwt.NewJWT()
		// parseToken 解析token包含的信息
		claims, err := j.ParseToken(token)
		if err != nil {
			if err == jwt.TokenExpired {
				resp.ErrorCode(types.TokenIsExpire, "授权已过期")
				c.Abort()
				return
			}
			resp.ErrorCode(types.TokenIsExpire, err.Error())
			c.Abort()
			return
		}
		// 继续交由下一个路由处理,并将解析出的信息传递下去
		//redisToken, _ := db.NewRedis().HGet(db.UserLogin, claims.ID)
		//if redisToken != token {
		//	resp.ErrorCode(types.TokenIsExpire, "授权已过期")
		//	c.Abort()
		//	return
		//}
		uid, _ := strconv.ParseInt(claims.ID, 10, 64)
		c.Set("uid", uid)
		method := c.Request.Method
		uri := c.Request.RequestURI
		// 鉴权
		isAuth := permission(uid, uri, method)
		if isAuth == false {
			resp.ErrorCode(types.NotAuth, "无访问权限!")
			c.Abort()
			return
		}
	}
}

func permission(uid int64, uri, method string) bool {
	// 调试阶段开启访问
	return true

	if method == "GET" {
		uri = uri[0:strings.Index(uri, "?")]
	}
	ruleLogic := logic2.NewRulesLogic()
	ruleList, err := ruleLogic.FindMenuRule(uid)
	if err != nil {
		Log.Log.Errorf("permission err:=%v", ruleList)
		return false
	}
	if _, ok := ruleList[uri+":"+method]; ok {
		return true
	}
	return false
}
